﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.CompilerServices;

using ConstructionBidOnline.DAL;
using ConstructionBidOnline.DAL.dsPageVideoTableAdapters;
using ConstructionBidOnline.Common;

namespace ConstructionBidOnline.Biz
{
    /// <summary>
    /// FAQ Business Object
    /// </summary>

    public class PageVideo : BOBase
    {


        #region Construction / Disposal

        /// <summary>
        /// Default constructor.
        /// </summary>
        protected PageVideo() { }

        #endregion

        #region Public Properties

        #region Instance Properties

        /// <summary>
        /// PKID of the PageVideo.
        /// </summary>
        public int VideoID
        {
            get { return _videoID; }
            set
            {
                if (_videoID != value)
                {
                    if (OnPropertyChanging("VideoID", _videoID, value))
                    {
                        int oldValue = _videoID;
                        _videoID = value;

                        OnPropertyChanged("VideoID", oldValue, value);
                    }
                }
            }
        }  private int _videoID = -1;

        /// <summary>
        /// Video Title.
        /// </summary>
        public string VideoTitle
        {
            get { return _videotitle; }
            set
            {
                if (_videotitle != value)
                {
                    if (OnPropertyChanging("VideoTitle", _videotitle, value))
                    {
                        string oldValue = _videotitle;
                        _videotitle = value;
                        OnPropertyChanged("VideoTitle", oldValue, value);
                    }
                }
            }
        }  private string _videotitle = null;


        /// <summary>
        /// Video File Name.
        /// </summary>
        public string VideoName
        {
            get { return _videoname; }
            set
            {
                if (_videoname != value)
                {
                    if (OnPropertyChanging("VideoName", _videoname, value))
                    {
                        string oldValue = _videoname;
                        _videoname = value;
                        OnPropertyChanged("VideoName", oldValue, value);
                    }
                }
            }
        }  private string _videoname = null;


        /// <summary>
        /// Video Description.
        /// </summary>
        public string VideoDescription
        {
            get { return _videodescription; }
            set
            {
                if (_videodescription != value)
                {
                    if (OnPropertyChanging("VideoDescription", _videodescription, value))
                    {
                        string oldValue = _videodescription;
                        _videodescription = value;
                        OnPropertyChanged("VideoDescription", oldValue, value);
                    }
                }
            }
        }  private string _videodescription = null;


        /// <summary>
        /// To be displayed on which page.
        /// </summary>
        public string DisplayPage
        {
            get { return _displaypage; }
            set
            {
                if (_displaypage != value)
                {
                    if (OnPropertyChanging("DisplayPage", _displaypage, value))
                    {
                        string oldValue = _displaypage;
                        _displaypage = value;
                        OnPropertyChanged("DisplayPage", oldValue, value);
                    }
                }
            }
        }  private string _displaypage = null;


        /// <summary>
        /// Date/time at which the Video was First uploaded.
        /// </summary>
        public DateTime? AddedDate
        {
            get { return _addedDate; }
            set
            {
                if (_addedDate != value)
                {
                    if (OnPropertyChanging("AddedDate", _addedDate, value))
                    {
                        DateTime? oldValue = _addedDate;
                        _addedDate = value;
                        OnPropertyChanged("AddedDate", oldValue, value);
                    }
                }
            }
        }  private DateTime? _addedDate = null;

        /// <summary>
        /// Date/time at which the video was updated.
        /// </summary>
        public DateTime? UpdatedDate
        {
            get { return _updatedDate; }
            set
            {
                if (_updatedDate != value)
                {
                    if (OnPropertyChanging("UpdatedDate", _updatedDate, value))
                    {
                        DateTime? oldValue = _updatedDate;
                        _updatedDate = value;
                        OnPropertyChanged("UpdatedDate", oldValue, value);
                    }
                }
            }
        }  private DateTime? _updatedDate = null;


        /// <summary>
        /// True iff the Admin has made this video Active (i.e. to be used in the application).
        /// </summary>
        public bool IsActive
        {
            get { return _isActive; }
            set
            {
                if (_isActive != value)
                {
                    if (OnPropertyChanging("IsActive", _isActive, value))
                    {
                        bool oldValue = _isActive;
                        _isActive = value;
                        OnPropertyChanged("IsActive", oldValue, value);
                    }
                }
            }
        }  private bool _isActive = false;

        #endregion

        #endregion

        #region Public Methods

        #region CreateNew

        /// <summary>
        /// Creates a new, empty PageVideo object.
        /// </summary>
        public static PageVideo CreateNew()
        {
            PageVideo obj = new PageVideo();

            // Switch state to Added prior to initializing property values.
            obj.ObjState = ObjectState.Added;

            obj.AddedDate = DateTime.Now;
            obj.UpdatedDate = DateTime.Now;
            obj.IsActive = true;
            return (obj);
        }


        [MethodImpl(MethodImplOptions.Synchronized)]
        public static PageVideo CreateNew(PageVideoCollection collection)
        {
            PageVideo obj = CreateNew();

            // Get next/unique ID for the new object.
            int minVal = 0;
            foreach (PageVideo pagevideo in collection)
            {
                if (pagevideo.VideoID < minVal)
                    minVal = pagevideo.VideoID;
            }
            obj.VideoID = --minVal;
            collection.Add(obj);

            return (obj);
        }

        #endregion

        #region GetAllPageVideos

        /// <summary>
        /// Returns a collection of all PageVideos.
        /// </summary>
        public static PageVideoCollection GetAllPageVideos()
        {
            PageVideoTableAdapter adapter = new PageVideoTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();

            dsPageVideo.PageVideoDataTable tbl = adapter.GetData(null);

            PageVideoCollection list = new PageVideoCollection();

            if (tbl.Rows.Count > 0)
            {
                foreach (dsPageVideo.PageVideoRow row in tbl.Rows)
                {
                    PageVideo pagevideo = new PageVideo();
                    RelationalToObject(pagevideo, row);
                    list.Add(pagevideo);
                }
            }

            return (list);
        }

        #endregion

        #region GetPageVideoByID

        /// <summary>
        /// Returns an PageVideo object for the specified 'VideoID' or null if no PageVideo with the specified parameter(s) exists.
        /// </summary>
        public static PageVideo GetPageVideoByID(int videoid)
        {
            PageVideoTableAdapter adapter = new PageVideoTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();

            dsPageVideo.PageVideoDataTable tbl = adapter.GetData(videoid);


            if (tbl.Rows.Count == 1)
            {
                PageVideo pagevideo = new PageVideo();
                RelationalToObject(pagevideo, tbl.Rows[0]);
                return (pagevideo);
            }
            else if (tbl.Rows.Count > 1)
                throw new ApplicationException("Database integrity error: Specified 'videoid' returned more than one record.");

            return (null);
        }

        #endregion

        #region GetPageVideoByDisplayPageNLatestVideo

        /// <summary>
        /// Returns an PageVideo object for the specified 'displaypage' or null if no PageVideo with the specified parameter(s) exists.
        /// </summary>
        public static PageVideo GetPageVideoByDisplayPageNLatestVideo(string displaypage)
        {
            PageVideoTableAdapter adapter = new PageVideoTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();

            dsPageVideo.PageVideoDataTable tbl = adapter.GetDataByDisplayPageNLatestVideo(displaypage);


            if (tbl.Rows.Count == 1)
            {
                PageVideo pagevideo = new PageVideo();
                RelationalToObject(pagevideo, tbl.Rows[0]);
                return (pagevideo);
            }
            else if (tbl.Rows.Count > 1)
                throw new ApplicationException("Database integrity error: Specified 'videoid' returned more than one record.");

            return (null);
        }

        #endregion

        #region Update

        /// <summary>
        /// Updates the specified PageVideo.
        /// </summary>
        public static void Update(PageVideo obj)
        {
            bool updatePageVideo = false;

            // Do not update invalid objects.
            if (!obj.Validate())
            {
                StringBuilder sb = new StringBuilder(2048);
                sb.Append("The object being updated has one or more invalid properties; the Update() operation for this object has been cancelled.\nError(s):");
                foreach (ValidationError err in obj.Errors)
                    sb.Append("\n* " + err.Element + ": " + err.Message);

                throw new InvalidObjectException(sb.ToString());
            }
            else
            {
                updatePageVideo = (obj.ObjState != ObjectState.Unchanged);

                if (!updatePageVideo)
                    return;
            }

            ObjectState originalObjectState = obj.ObjState;

            dsPageVideo.PageVideoDataTable tbl = null;
            if (updatePageVideo)
            {
                PageVideoTableAdapter adapter = new PageVideoTableAdapter();
                adapter.Connection = AppSettings.GetDbConn();

                tbl = new dsPageVideo.PageVideoDataTable();
                dsPageVideo.PageVideoRow row = tbl.NewPageVideoRow();
                ObjectToRelational(obj, tbl, row);

                adapter.Update(tbl);

                if (originalObjectState == ObjectState.Deleted)
                    obj = null;
                else RelationalToObject(obj, tbl.Rows[0]);
            }
        }

        #endregion

        #region Validate

        /// <summary>
        /// Validates the object based on its properties at the time of the call; updates the Errors property.
        /// </summary>
        public override bool Validate()
        {
            Errors.Clear();

            if (ObjState == ObjectState.Unchanged)
            {
                // By definition, unchanged objects are valid.
                return (true);
            }
            else if (ObjState == ObjectState.Uninitialized)
            {
                Errors.Add(new ValidationError("object", "Object is uninitialized.", ValidationError.Severity.Error));

                // No need to proceed past this error.
                return (false);
            }
            else if ((ObjState == ObjectState.Deleted) && (VideoID <= 0))
            {
                // Deleted items must have 'real' (i.e. non-negative, non-zero) key(s) to be valid.
                Errors.Add(new ValidationError("VideoID", "Deleted object has an invalid PKID.", ValidationError.Severity.Error));

                // No need to proceed past this error.
                return (false);
            }
            else  // ObjState == Added | Modified
            {

                // UserName is required.
                if ((VideoName == null) || (VideoName.Trim().Length == 0))
                {
                    Errors.Add(new ValidationError("VideoName", "File Name is required.", ValidationError.Severity.Error));
                }
                else if (ObjState == ObjectState.Added)
                {

                }

            }

            return (Errors.Count == 0);
        }

        #endregion

        #region ToString

        /// <summary>
        /// User-friendly string represetation of this object.
        /// </summary>
        public override string ToString()
        {
            return (String.Format("PageVideo: VideoID={0}, VideoName={1}, {2}", VideoID, VideoName, VideoDescription));
        }

        #endregion

        #endregion

        #region Privates


        #endregion

    }

    /// <summary>
    /// Collection of 0 or more PageVideo objects.
    /// </summary>

    public class PageVideoCollection : List<PageVideo>
    {
        #region Types

        public class UserComparer : IComparer<PageVideo>
        {
            public int Compare(PageVideo pv1, PageVideo pv2)
            {
                return (String.Compare(pv1.VideoName, pv2.VideoName));
            }
        }

        #endregion

        #region Public Methods

        #region FindByVideoID

        public PageVideo FindByVideoID(int videoID)
        {
            for (int ndx = 0; ndx < this.Count; ndx++)
                if (this[ndx].VideoID == videoID)
                    return (this[ndx]);

            return (null);
        }

        #endregion

        #region FindVideoByFileName

        /// <summary>
        /// Case insensitve compare.
        /// </summary>
        public PageVideo FindVideoByFileNmae(string filename)
        {
            for (int ndx = 0; ndx < this.Count; ndx++)
                if (this[ndx].VideoName == filename)
                    return (this[ndx]);

            return (null);
        }

        #endregion

        #endregion
    }
}
